package com.zhuzi.guicollect.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Connection;
import org.jsoup.Jsoup;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author: MI
 * @Date: 2021/10/25/20:42
 * @Description:
 */
@Slf4j
public class SysUtils {
    public static void sleep(int delay) {
        try {
            TimeUnit.SECONDS.sleep(delay);
        } catch (InterruptedException e) {
        }
    }

    public static boolean isNumber(String str) {
        try {
            new BigDecimal(str);
            return true;
        } catch (Exception e) {
        }
        return false;
    }

    public static String getLoginStr() {
        if (StringUtils.isBlank(loginStr)) {
            init();
        }
        return loginStr;
    }

    public static String loginStr = "";
    /**
     * 访问的关键字
     */
    public static final String COOKIE_KEY_NAME = "kbzw__user_login";

    private static void init() {
        String urlLogin = "https://www.jisilu.cn/account/ajax/login_process/";
        Map<String, String> loginDataMap = new HashMap<>(4);
        loginDataMap.put("return_url", "https://www.jisilu.cn/");
        //my
        loginDataMap.put("user_name", "533c791817b16ee002a06a525f98e5dc");
        loginDataMap.put("password", "6a367d98cc9cf7fba310074afcbfdca1");
        loginDataMap.put("net_auto_login", "1");
        loginDataMap.put("_post_type", "ajax");
        loginDataMap.put("aes", "1");
        final Connection connect = Jsoup.connect(urlLogin);
        try {
            Connection.Response response = connect.method(Connection.Method.POST).ignoreContentType(true)
                    .ignoreHttpErrors(true)
                    .data(loginDataMap)
                    .followRedirects(false)
                    .execute();
            final Map<String, String> cookies = response.cookies();
            loginStr = COOKIE_KEY_NAME + "=" + cookies.get(COOKIE_KEY_NAME);
            log.info("登陆访问~成功：{}", loginStr);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("登陆访问失败:{}", e);
        }
    }
}
